package tresp.utils.team;

import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;

import robocode.HitByBulletEvent;
import tresp.bthreads.BThread;
import tresp.bthreads.BThreadType;
import tresp.coordinator.ICoordinator;
import tresp.utils.BThreadVote;
import tresp.utils.ITankInfo;
import tresp.utils.logging.MyLogger;


/**
 * <b>AvoidHittingFromTeamMates</b>
 * 
 * 
 * @author <font color="blue">Maxim Kirilov</font>
 *
 */
public class AvoidHittingFromTeamMates extends BThread {

    private static Logger logger = MyLogger.getLogger( AvoidHittingFromTeamMates.class );
    
    private AtomicReference<HitByBulletEvent> lastHitByBulletEvent;
    
    private ITankInfo tankInfo;
    
    
    public AvoidHittingFromTeamMates(ICoordinator<BThreadVote> coordinator) {
	super(coordinator);
	tankInfo = coordinator.getTankInfo();
	lastHitByBulletEvent = new AtomicReference<HitByBulletEvent>();
	logger.info("AvoidHittingFromTeamMates created successfully");
	weight = 50D;
    }

    @Override
    public void vote() {
	
	HitByBulletEvent e = lastHitByBulletEvent.getAndSet( null );
	if ( e != null && tankInfo.isTeammate( e.getName() )){
	    BThreadVote vote = createBThreadVote(BThreadType.SEND_MESSAGE, weight, 0D);
	    vote.setRecipientName( e.getName() );
	    vote.setMessage(new TeamMateMessage(TeamCommandType.HOLD_FIRE) );
//	    logger.info("sending message to: "+ e.getName()+ " hold fire.");
	    coordinator.vote( vote );
	}

    }

    @Override
    public String getName() {
	return "AvoidHittingFromTeamMates";
    }
    
    @Override
    public void onHitByBullet(HitByBulletEvent event){
	lastHitByBulletEvent.set( event );
    }

}
